package com.zzl.ov_library.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzl.ov_library.dto.Result;
import com.zzl.ov_library.entity.Inventory;
import com.zzl.ov_library.service.BooksService;
import com.zzl.ov_library.service.BranchService;
import com.zzl.ov_library.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private BooksService booksService;

    @Autowired
    private BranchService branchService;

    @Autowired
    private BorrowRecordController borrowRecordController;

    //新增图书库存
    @PostMapping("/inventory/add")
    public Result addInventory(Integer branchId, Integer bookId, Integer count) {
        //通过branchId和bookId查询库存是否已存在
        Inventory inventory = inventoryService.getOne(Wrappers.lambdaQuery(Inventory.class)
                .eq(Inventory::getBranchId, branchId)
                .eq(Inventory::getBookId, bookId));
        //如果存在，则更新库存数量
        if (inventory != null) {
            inventory.setTotalCount(inventory.getTotalCount() + count);
            inventory.setAvailableCount(inventory.getAvailableCount() + count);
            return inventoryService.updateById(inventory) ? Result.ok().setMsg("库存更新成功") : Result.fail().setMsg("库存更新失败");
        } else {
            //如果不存在，则新增一条库存记录
            Inventory newInventory = new Inventory();
            newInventory.setBranchId(branchId);
            newInventory.setBookId(bookId);
            newInventory.setTotalCount(count);
            newInventory.setAvailableCount(count);
            return inventoryService.save(newInventory) ? Result.ok().setMsg("库存新增成功") : Result.fail().setMsg("库存新增失败");
        }
    }

    //更新库存可借数量
    @PutMapping("/inventory/update")
    public Result updateInventory(@RequestParam Integer inventoryId, @RequestParam Integer availableCount) {
        Inventory inventory = inventoryService.getById(inventoryId);
        if (inventory == null)
            return Result.fail().setMsg("库存不存在");
        if (availableCount < 0 && inventory.getAvailableCount() < Math.abs(availableCount)) {
            return Result.fail().setMsg("库存不足");
        }
        if (inventory.getTotalCount() < inventory.getAvailableCount() + availableCount)
            return Result.fail().setMsg("可借数不能大于库存数");
        inventory.setAvailableCount(inventory.getAvailableCount() + availableCount);

        return inventoryService.updateById(inventory) ? Result.ok().setMsg("更新成功") : Result.fail().setMsg("更新失败");
    }

    //通过bookId查询库存
    @GetMapping("/inventory/queryByBookId/{bookId}")
    public Result queryByBookId(@PathVariable Integer bookId) {
        System.out.println("bookId:" + bookId);
        //通过bookId查询库存，返回库存列表
        List<Inventory> inventoryList = inventoryService.list(Wrappers.lambdaQuery(Inventory.class)
                .eq(Inventory::getBookId, bookId));
        System.out.println("inventoryList:" + inventoryList);
        return inventoryList.size() > 0 ? Result.ok().setData(inventoryList) : Result.fail().setMsg("库存不存在");
    }


    //更新库存可借数量并新增借阅记录
    @PutMapping("/inventory/updateAndAddRecord")
    @Transactional
    public Result updateInventoryAndAddRecord(@RequestParam Integer inventoryId, @RequestParam Integer availableCount, @RequestParam Integer userId) {
        Inventory inventory = inventoryService.getById(inventoryId);
        if (inventory == null)
            return Result.fail().setMsg("库存不存在");
        if (availableCount < 0 && inventory.getAvailableCount() < Math.abs(availableCount)) {
            return Result.fail().setMsg("库存不足");
        }
        inventory.setAvailableCount(inventory.getAvailableCount() + availableCount);

        borrowRecordController.addBorrowRecord(userId, inventory.getBookId(), inventory.getBranchId());
        inventoryService.updateById(inventory);

        return Result.ok().setMsg("更新成功");
    }

    //还书-增加库存数量
    @PutMapping("/inventory/return")
    public Result returnBook(@RequestParam Integer branchId, @RequestParam Integer bookId) {
        Inventory inventory = inventoryService.getOne(Wrappers.lambdaQuery(Inventory.class)
                .eq(Inventory::getBranchId, branchId)
                .eq(Inventory::getBookId, bookId));
        if (inventory != null) {
            inventory.setAvailableCount(inventory.getAvailableCount() + 1);
        } else {
            inventory = new Inventory();
            inventory.setBranchId(branchId);
            inventory.setBookId(bookId);
            inventory.setAvailableCount(1);
        }
        return inventoryService.saveOrUpdate(inventory) ? Result.ok().setMsg("更新成功") : Result.fail().setMsg("更新失败");
    }

    //随机添加库存
    @PostMapping("/inventory/addRandom")
    public Result addRandom() {
        //循环一百次
        for (int i = 0; i < 100; i++) {
            //随机生成branchId，1~7
            int branchId = (int) (Math.random() * 7 + 1);
            //调用bookService获取books的count
            long count = booksService.count();
            //生成1~count的随机数
            int random = (int) (Math.random() * count + 1);
            //随机生成库存数，0~3
            int availableCount = (int) (Math.random() * 3 + 0);

            Inventory inventory = new Inventory();
            inventory.setBranchId(branchId);
            inventory.setBookId(random);
            inventory.setAvailableCount(availableCount);

            if (inventoryService.getOne(Wrappers.lambdaQuery(Inventory.class)
                    .eq(Inventory::getBranchId, branchId)
                    .eq(Inventory::getBookId, random)) == null) {
                //如果不存在，则新增一条库存记录
                inventoryService.save(inventory);
            }

        }
        return Result.ok().setMsg("库存添加成功");
    }

}
